export default {
  namespaced: true,
  state () {
    return {
      goodList: [
        {
          id: 1,
          name: '诸葛亮',
          price: 1000,
          num: 1,
          checked: false
        },
        {
          id: 2,
          name: '蔡文姬',
          price: 1500,
          num: 1,
          checked: false
        },
        {
          id: 3,
          name: '妲己',
          price: 2000,
          num: 1,
          checked: false
        },
        {
          id: 4,
          name: '鲁班',
          price: 2200,
          num: 1,
          checked: false
        }
      ]
    }
  },

  mutations: {
    delItem (state, payload) {
      const index = state.goodList.findIndex(item => item.id === payload.id)
      state.goodList.splice(index, 1)
    },
    changeChecked (state, payload) {
      const res = state.goodList.find(item => item.id === payload.id)
      res.checked = !res.checked
    },
    changeIsAll (state, payload) {
      state.goodList.forEach(item => { item.checked = payload.value })
    },
    sumCount (state, payload) {
      const res = state.goodList.find(item => item.id === payload.id)
      res.num++
    },
    subCount (state, payload) {
      const res = state.goodList.find(item => item.id === payload.id)
      if (res.num > 1) {
        res.num--
      }
    }
  },

  getters: {
    totalPrice (state) {
      return state.goodList.reduce((prev, item) => {
        if (item.checked === true) {
          (prev += item.price * item.num)
        }
        return prev
      }, 0)
    }
  }

}
